package main

import (
	"fmt"
	"gold_task/db"
	"gold_task/service"
	"gold_task/util"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/pkg/errors"
	"github.com/rifflock/lfshook"
	log "github.com/sirupsen/logrus"
)

var (
	superOpenIdMap = map[string]bool{}
)

func main() {
	ConfigLocalFilesystemLogger("/app", "log", 168*time.Hour, time.Hour)
	if err := db.Init(); err != nil {
		panic(fmt.Sprintf("mysql init failed with %+v", err))
	}
	log.Println("init db success")
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		//输出json结果给调用方
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Use(func(c *gin.Context) {
		log.Printf("ginCtx.request = %v", util.ToString(c.Request))
		c.GetHeader("X-Wx-Appid")
		if c.GetHeader("X-Wx-Openid") == "" {
			c.AbortWithError(400, errors.New("illegal open_id"))
			return
		}
		if c.GetHeader("X-Wx-Appid") != "wx639ceb1d0fe57435" {
			c.AbortWithError(400, errors.New("illegal app_id"))
			return
		}
		c.Next()
	})
	r.GET("/", service.GinIndexHandler)
	r.GET("/ut", func(c *gin.Context) {
		if superOpenIdMap[c.GetHeader("X-Wx-Openid")] {
			c.JSON(200, gin.H{
				"ut": "1",
			})
		} else {
			c.JSON(200, gin.H{
				"ut": "0",
			})
		}
	})
	r.GET("/tasks", service.GetTaskList)
	r.GET("/review_items", service.GetMyReviewItems)
	log.Fatal(r.Run(":80"))

	//http.HandleFunc("/", service.IndexHandler)
	//http.HandleFunc("/api/count", service.CounterHandler)
	//
	//log.Fatal(http.ListenAndServe(":80", nil))
}
func ConfigLocalFilesystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
	baseLogPaht := path.Join(logPath, logFileName)
	writer, err := rotatelogs.New(
		baseLogPaht+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(baseLogPaht),      // 生成软链，指向最新日志文件
		rotatelogs.WithMaxAge(maxAge),             // 文件最大保存时间
		rotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔
	)
	if err != nil {
		log.Errorf("config local file system logger error. %+v", errors.WithStack(err))
	}
	lfHook := lfshook.NewHook(lfshook.WriterMap{
		log.DebugLevel: writer, // 为不同级别设置不同的输出目的
		log.InfoLevel:  writer,
		log.WarnLevel:  writer,
		log.ErrorLevel: writer,
		log.FatalLevel: writer,
		log.PanicLevel: writer,
	}, &log.TextFormatter{})
	log.SetReportCaller(true)
	log.AddHook(lfHook)
}
